package com.mofang.powerdekorhelper.utils;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.mofang.powerdekorhelper.service.HeartbeatService;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;

/**
 * Created by luofei on 2017/12/21 0021.
 * 说明：
 */

public class ConnectionUtils {

    private String TAG = "pConnectionUtils";

    private String wsUrl;

    private static ConnectionUtils connectionUtils;
    private Context mContext;
    private WebSocketConnection mConnect = new WebSocketConnection();
    private HeartbeatService heartbeatService;

    public static ConnectionUtils getInstance() {
        if (connectionUtils == null) {
            connectionUtils = new ConnectionUtils();
        }
        return connectionUtils;
    }

    public void init(Context context, String wsUrl) {
        this.mContext = context;
        this.wsUrl = wsUrl;
    }

    /**
     * websocket连接，接收服务器消息
     */
    public void connect() {
        Log.i(TAG, "------------>ws connecting....");
        try {
            mConnect.connect(wsUrl, new WebSocketHandler() {
                @Override
                public void onOpen() {
                    Log.i(TAG, "------------>连接成功");
                    heartbeatService = new HeartbeatService();
                    heartbeatService.startService(mContext);
                }

                @Override
                public void onTextMessage(String payload) {
                    Log.i(TAG, "------------>onTextMessage------>" + payload);
                    if ("exit".equals(payload)) {
                        mConnect.disconnect();
                        Intent mIntent = new Intent("DisConnection");
                        mContext.sendBroadcast(mIntent);
                    }
                }

                @Override
                public void onClose(int code, String reason) {
                    Log.i(TAG, "------------>断开连接");
                    Intent intent = new Intent(mContext, HeartbeatService.class);
                    mContext.stopService(intent);
                }
            });
        } catch (WebSocketException e) {
            Log.i(TAG, "WebSocketException------------>" + e.getMessage());
        }
    }

    public void send(String message) {
        Log.i(TAG, "send------------>" + message);
       /* if (mConnect != null) {
            mConnect.sendTextMessage(message);
        }*/
    }

    public void exit() {
        if (mConnect != null) {
            try {
                mConnect.sendTextMessage("exit");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
